import Taro from '@tarojs/taro'
import { HTTP_STATUS } from '../consts/status'
import { MNP_REQUEST_DEFAULT_CONFIG } from '../config/index'

const taroDefaultRequest = {
  url: '',
  method: 'GET',
  dataType: 'json',
  responseType: 'text',
  header: {
    'content-type': 'application/json',
    Authorization: '',
    Accept: 'application/json'
  }
}

const packRequest = newRequestObj => {
  return Taro.request(newRequestObj)
    .then(resp => {
      // handle HTTP_STATUS Code
      // console.log(resp)
      let errorMessage = ''
      let errorObj = { code: '', message: '' }
      switch (resp.statusCode) {
        case HTTP_STATUS.SUCCESS:
          if (typeof resp.data.code !== 'undefined') {
            switch (resp.data.code) {
              case 0:
                // 正常交互 不需要收集
                return resp.data.data
              default:
                errorObj = { ...resp.data }
                break
            }
          }
        case HTTP_STATUS.CLIENT_ERROR:
          errorMessage = '客户端错误'
          break
        case HTTP_STATUS.FORBIDDEN:
          errorMessage = '禁止请求'
          break
        case HTTP_STATUS.NOT_FOUND:
          errorMessage = '未发现服务, 请联系客服'
          break
        case HTTP_STATUS.SERVER_ERROR:
          errorMessage = '服务器问题, 请联系客服'
          break
        default:
          errorMessage = '未知问题，请联系客服'
          break
      }
      // 统一在catch中catch
      // TODO handle the errorMessage with modal
      if (errorMessage) {
        return Promise.reject(errorMessage)
      } else if (errorObj.code) {
        return Promise.reject(errorObj)
      }
    })
    .catch(
      (e): any => {
        console.error(e, 'requesterror')
        // common error
        if (typeof e === 'string') {
          // Taro.showToast({title:e, icon:'error'})
          return Promise.reject(e)
        } else if (e instanceof Object) {
          return Promise.reject(e.message)
        }
      }
    )
}

const request = ({
  baseURL = MNP_REQUEST_DEFAULT_CONFIG.baseURL,
  url,
  data,
  method,
  absolute = false
}) => {
  const path = absolute ? url : baseURL + url
  // const path = taroDefaultRequest.url + url
  const newRequestObj = {
    ...taroDefaultRequest,
    url: path,
    method,
    data
  }
  return packRequest(newRequestObj)
}

export default request
